//
//  IncomeViewController.m
//  NiuBanJin
//
//  Created by Billy on 15/10/17.
//  Copyright © 2015年 zzjr. All rights reserved.
//

#import "IncomeViewController.h"
#import "Income.h"
#import "AssetList.h"
#import "IncomeViewCell.h"

@interface IncomeViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *mutableArray_data; //数据源,所有的income对象
@property(nonatomic, assign) int pageNumber; // 当前访问的页数
@property(nonatomic, assign) CGFloat max_valueProfit; // 加载tableview的标志 为1加载，为2不加载

@end

@implementation IncomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationItem setTitle:@"收益记录"];
    
    [self.view addSubview:self.tableView]; //将来优化一下，只有当获得数据的时候才去加载tableview,belazy
    
    self.pageNumber = 1; //初始化当前访问页数
    self.max_valueProfit = 50.0; //默认值
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self getDataFromServer];
}

- (void) getDataFromServer {
    
    NSDictionary *dic_params =  @{@"userId":GETCURRENTUSERINOBYPRAMETERES(user_userId),@"type":@"3",@"pageNum":[NSString stringWithFormat:@"%d",self.pageNumber]};
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [[NetworkUtil sharedNetworkUtil] zzjrUserAssetsListByParmeteres:dic_params transferResultUsingBlock:^(id parsedData, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.tableView.header endRefreshing]; //停止刷新
        [self.tableView.footer endRefreshing];
        
        if (!error) {
            
            //得到数据后做刷新操作
            // 因为有下拉刷新，所以这儿不能光想着clear ,按pageNumber来区分，如果大于2表明有下拉刷新要保存历史记录
            
            
            if (self.pageNumber > 1) { //保存历史数据
                
                [self.mutableArray_data addObjectsFromArray:parsedData];
                
            } else {
                
                self.mutableArray_data = parsedData;
                
                self.max_valueProfit = [self getMaxValueInArray:self.mutableArray_data];
   
                if ([self.mutableArray_data count] == 0) { //判定什么时候显示空数据几个字
                    
                    EmptyDataView *view_empty = [[EmptyDataView alloc]initWithFrame:self.tableView.frame];
                    [self.view addSubview:view_empty]; // 加过一次后就永远存在了，要想办法去掉
                }else {
                    
                    [self.view bringSubviewToFront:self.tableView]; //把tableview放前面就行了，不用remove再加,省资源
                }
            }

            [self.tableView reloadData];
        }else {
            
            [UsefulUtil showAlertView:error.description]; //现阶段直接把错误详情展示出来
        }
    }];
}

- (CGFloat) getMaxValueInArray:(NSMutableArray *) array {
    
   NSArray *tmp = [self.mutableArray_data sortedArrayUsingComparator:
     ^NSComparisonResult(AssetList *obj1, AssetList *obj2) { //计算返回来的值中的最大值
         
         CGFloat value1 = [[[obj1.assetList_value componentsSeparatedByString:@"+"] lastObject] floatValue];
         CGFloat value2 = [[[obj2.assetList_value componentsSeparatedByString:@"+"] lastObject] floatValue];
         // 先按照姓排序
         
         return value1 > value2;
     }];
    
    NSString *str_max_value = [[tmp lastObject] valueForKey:@"assetList_value"];
    
    return [[[str_max_value componentsSeparatedByString:@"+"] lastObject ] floatValue];
}

#pragma mark - TableView datasource && delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.mutableArray_data count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView setRowHeight:MULTIPLYHEIGHT(95.0/2)];
    
    static NSString *identifer = @"cellIncome" ;
    
    IncomeViewCell *cell = (IncomeViewCell *)[tableView dequeueReusableCellWithIdentifier:identifer];
    
    if (!cell) {
        
        cell = [[IncomeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
    }
    
    if (indexPath.row == 0) {
        
        [cell setColor_cell:REDCOLOR];
    }
    
    [cell setIncome:self.mutableArray_data[indexPath.row]];
    [cell setDayProfitMax:self.max_valueProfit];
    
    return  cell;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view_header = [UsefulUtil viewCreationWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT(215.0/2)) backgroundColor:[UIColor whiteColor] backGroundImage:nil];
    
    // 总收益
    UILabel *label_assetPrompt = [UsefulUtil labelCreationWithFrame:CGRectMake(MULTIPLYWIDTH(300.0/2), MULTIPLYHEIGHT(42.0/2), MULTIPLYWIDTH(166.0/2), MULTIPLYHEIGHT(30.0/2)) textColor:[UsefulUtil colorWithHexString:@"#434343"] fontName:[UIFont systemFontOfSize:15.0] text:@"累计收益 (元)"];
    
    [label_assetPrompt setTextAlignment:NSTextAlignmentCenter];
    [view_header addSubview:label_assetPrompt];
    
    UILabel *label_assetValue = [UsefulUtil labelCreationWithFrame:CGRectMake(0, CGRectGetMaxY(label_assetPrompt.frame) + MULTIPLYHEIGHT(36.0/2), SCREEN_WIDTH, MULTIPLYHEIGHT(60.0/2)) textColor:REDCOLOR fontName:[UIFont systemFontOfSize:(iPhone4?30:40)] text:(self.str_totayProfit == nil)?@"0.00":self.str_totayProfit];

    [label_assetValue setTextAlignment:NSTextAlignmentCenter];
    [view_header addSubview:label_assetValue];
    
    UIView *view_Sep = [UsefulUtil viewCreationWithFrame:CGRectMake(0, MULTIPLYHEIGHT(200.0/2), SCREEN_WIDTH, MULTIPLYHEIGHT(15.0/2)) backgroundColor:BASECOLOR backGroundImage:nil];
    
    [view_header addSubview:view_Sep];
  
    return view_header;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return MULTIPLYHEIGHT(215.0/2);
}

#pragma mark - setter methods

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
        
        [_tableView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView setBackgroundColor:BASECOLOR];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        [_tableView setAllowsSelection:NO];
    }
    
    return  _tableView;
}

- (NSMutableArray *)mutableArray_data {
    
    if (!_mutableArray_data) {
        
        _mutableArray_data = [NSMutableArray array];
    }
    
    return  _mutableArray_data;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
